package models

import beans.Record
import com.jfinal.plugin.activerecord.Model
import services.RecordState

class RecordM: Model<RecordM>(){
    companion object{
        val AGENT by lazy {
            RecordM()
        }
        const val TABLE_NAME = "records"
        const val ID = "id"
        const val TITLE = "title"
        const val DESC = "description"
        const val IMGS = "images"
        const val PRICE = "price"
        const val MAIN_CLASS = "main_class"
        const val TAGS = "tags"
        const val TIME = "time"
        const val LONGITUDE = "longitude"
        const val LATITUDE = "latitude"
        const val STATE = "state"
        const val ZONE = "zone"
        const val USER_ID = "user_id"

        const val ITEM_NUM_PER_PAGE = 40

        fun findRecordByUserId(userId: Int): List<Record>{
            val models = AGENT.find("select * from $TABLE_NAME where $USER_ID = $userId")
            return models.map {
                Record.from(it)
            }
        }

        fun findRecordInZonesWithPageAndState(zones: List<String>, page: Int, state: Int): List<Record>{
            val sb = StringBuffer().apply {
                zones.forEach{
                    append("zone = ").append("\'$it\'").append(" or ")
                }
                delete(length-" or ".length, length)
            }
            //println("zones : $sb")
            val page = AGENT.paginate(page, ITEM_NUM_PER_PAGE,
                    "select *",
                    "from $TABLE_NAME where $STATE = $state and ( $sb )")
            return page.list.map { Record.from(it) }
        }

        fun findRecordWithPageAndState(page: Int, state: Int): List<Record>{
            val page = AGENT.paginate(page, ITEM_NUM_PER_PAGE,
                    "select *",
                    "from $TABLE_NAME where $STATE = $state")
            return page.list.map { Record.from(it) }
        }

        fun findSoldRecords(userId: Int): List<Record>{
            val list = AGENT.find("select * from $TABLE_NAME where $USER_ID = ? and $STATE = ?", userId, RecordState.SOLD)
            return list.map { Record.from(it) }
        }

        fun findReviewRecords(): List<Record>{
            val list = AGENT.find("select * from $TABLE_NAME where $STATE = ?", RecordState.REVIEW)
            return list.map { Record.from(it) }
        }
    }
}